﻿#define _CRT_SECURE_NO_WARNINGS
#include"List.h"
//双向带头循环
LTNode* BuyListNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		printf("开辟失败");
		perror("malloc");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

LTNode* LTInit()
{
	LTNode* pphead = BuyListNode(-1);
	pphead->next = pphead;
	pphead->prev = pphead;
	return pphead;
}
void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead;
	while (cur!=phead)
	{
		free(cur);
		cur = cur->next;
	}

}
void LTPrint(LTNode* phead)
{
	assert(phead);

	printf("<=head=>");
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode*node=BuyListNode(x);
	LTNode* tail = phead->prev;
	node->prev = tail;
	tail->next = node;
	phead->prev = node;
	node->next=phead;
}
void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));//判断非空不能删
	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;
	tailprev->next = phead;
	phead->prev = tailprev;
	free(tail);
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* node = BuyListNode(x);
	LTNode* next = phead->next;
	node->next = next;
	node->prev = phead;
	phead->next = node;
	next->prev = node;

}
void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));
	LTNode* first = phead->next;
	LTNode* next = first->next;
	free(first);
	phead->next = next;
	next->prev = phead;
}

// 
void LTInsert(LTNode* pos, LTDataType x) //在pos后面插入
{
	assert(pos);
	LTNode* node = BuyListNode(x);
	LTNode* next = pos->next;
	node->next = next;
	node->prev = pos;
	next->prev = node;
	pos->next = node;
}
void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* posnext = pos->next;
	LTNode* posprev = pos->prev;
	free(pos);
	posnext->prev = posprev;
	posprev->next = posnext;

}
